//
//  ViewController.swift
//  EggTimer
//
//  Created by Huan Di on 12/01/2018.
//  Copyright © 2018 DHuan. All rights reserved.
//

import Cocoa
import AVFoundation

class ViewController: NSViewController {
    
    // sound player
    var soundPlayer: AVAudioPlayer?

    // UI visuals
    @IBOutlet weak var timeLeftField: NSTextField!
    @IBOutlet weak var eggImageView: NSImageView!
    
    @IBOutlet weak var startButton: NSButton!
    @IBOutlet weak var stopButton: NSButton!
    @IBOutlet weak var resetButton: NSButton!
    
    // model
    var eggTimer = EggTimer()
    var preference = Preferences()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        eggTimer.delegate = self
        setupPreference()
    }
    
    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    // UI actions
    @IBAction func startButtonClicked(_ sender: NSButton) {
        if eggTimer.isPaused {
            eggTimer.resumeTimer()
        }
        else{
            eggTimer.duration = preference.selectedTime
            eggTimer.startTimer()
            prepareSound()
        }
        configButtonsAndMenus()
    }
    @IBAction func stopButtonClicked(_ sender: NSButton) {
        eggTimer.stopTimer()
        configButtonsAndMenus()
    }
    @IBAction func resetButtonClicked(_ sender: NSButton) {
        eggTimer.resetTimer()
        updateDisplay(for: preference.selectedTime)
        configButtonsAndMenus()
    }
    
}

extension ViewController {
    
    func updateDisplay(for timerRemaining: TimeInterval){
        timeLeftField.stringValue = textToDisplay(for: timerRemaining)
        eggImageView.image = imageToDisplay(for: timerRemaining)
    }
    
    private func textToDisplay(for timeRemaining: TimeInterval) -> String {
        if timeRemaining == 0 {
            return "Done!"
        }
        
        let minutesRemaining = floor(timeRemaining / 60)
        let secondsRemaining = timeRemaining - (minutesRemaining * 60)
        
        let secondsDisplay = String(format: "%02d", Int(secondsRemaining))
        let timerRemainingDisplay = "\(Int(minutesRemaining)):\(secondsDisplay)"
        
        return timerRemainingDisplay
    }
    
    private func imageToDisplay(for timeRemaining: TimeInterval) -> NSImage?{
        let percentage = 100 - (timeRemaining/eggTimer.duration * 100)
    
        var imageName : String
        
        switch percentage {
        case 0..<25:
            imageName = "0"
        case 25..<50:
            imageName = "25"
        case 50..<75:
            imageName = "50"
        case 75..<100:
            imageName = "75"
        default:
            imageName = "100"
        }
        
        if eggTimer.isStopped{
            imageName = (timeRemaining == 0) ? "100":"stopped"
        }
        return NSImage(named: NSImage.Name(rawValue: imageName))
    }



    func configButtonsAndMenus(){

        switch eggTimer {
        case let x where x.isStopped:
            reflexTimerStatus(timerStatus : EggTimerActorStatus(enableStart:true, enableStop: false, enableReset:false))
        case let x where x.isPaused:
            reflexTimerStatus(timerStatus : EggTimerActorStatus(enableStart:true, enableStop: false, enableReset:true))
        default:
            reflexTimerStatus(timerStatus : EggTimerActorStatus(enableStart:false, enableStop: true, enableReset:false))
        }

    }
    
    
    private func reflexTimerStatus (timerStatus: EggTimerActorStatus){
        // enable or disable buttons
        startButton.isEnabled = timerStatus.enableStart
        stopButton.isEnabled = timerStatus.enableStop
        resetButton.isEnabled = timerStatus.enableReset
        // enable or disable menus
        if let appDelegate = NSApplication.shared.delegate as? AppDelegate {
            appDelegate.enableMenus(timerStatus: timerStatus)
            
        }
    }
}

extension ViewController:EggTimerProtocol {
    func timeRemainOnTimer(_ timer: EggTimer, timeRemaining: TimeInterval) {
        updateDisplay(for: timeRemaining)
    }
    func timerHasFinished(_ timer: EggTimer) {
        playSound()
        updateDisplay(for: 0)
        stopButtonClicked(stopButton)
    }
}

extension ViewController{
    func updateFromPreference(){
        self.eggTimer.duration = self.preference.selectedTime
        self.resetButtonClicked(self.resetButton)
    }
    func setupPreference() -> Void {
        updateDisplay(for: preference.selectedTime)
        let notificationName = Notification.Name(rawValue:"PreferenceChanged")
        NotificationCenter.default.addObserver(forName: notificationName, object: nil, queue: nil) { (notfication) in
            self.checkForResetAfterPreferenceChange()
        }
    }
    func checkForResetAfterPreferenceChange(){
        if eggTimer.isPaused || eggTimer.isStopped {
            self.updateFromPreference()
            return
        }
        
        let alert = NSAlert()
        alert.messageText = "Reset timer with the new settings?"
        alert.informativeText = "Reset will stop your current timer!"
        alert.alertStyle = .warning
        
    
        
        alert.addButton(withTitle: "Reset")
        alert.addButton(withTitle: "Cancel")
        alert.icon = NSImage(named: NSImage.Name(rawValue: "AppIcon"))
        
        let response = alert.runModal()
        if response == NSApplication.ModalResponse.alertFirstButtonReturn {
            self.updateFromPreference()
        }
    }
}

extension ViewController {
    func prepareSound (){
        guard let audioFileUrl = Bundle.main.url(forResource: "ding", withExtension: "mp3") else {
            return
        }
        do {
            soundPlayer = try AVAudioPlayer(contentsOf: audioFileUrl)
            soundPlayer?.prepareToPlay()
        } catch  {
            print("Sound player not available:\(error)")
        }
    }
    func playSound(){
        soundPlayer?.play()
    }
}
